<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/xizhongren8980/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/xizhongren8980/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/xizhongren8980/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/xizhongren8980/images/logo.svg" color="#222">

<link rel="stylesheet" href="/xizhongren8980/css/main.css">


<link rel="stylesheet" href="/xizhongren8980/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"gitee.com","root":"/xizhongren8980/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="正则表达式是一种强大且灵活的文本处理工具。它提供了一种完全通用的方式，能够解决字符串处理相关的问题：匹配、选择、编辑以及验证。">
<meta property="og:type" content="article">
<meta property="og:title" content="正则表达式">
<meta property="og:url" content="https://gitee.com/xizhongren8980/xizhongren8980.git/2020/03/10/%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F/index.html">
<meta property="og:site_name" content="一杯茶一包烟，一个BUG改一天">
<meta property="og:description" content="正则表达式是一种强大且灵活的文本处理工具。它提供了一种完全通用的方式，能够解决字符串处理相关的问题：匹配、选择、编辑以及验证。">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2020-03-10T05:50:11.245Z">
<meta property="article:modified_time" content="2020-03-10T07:05:44.588Z">
<meta property="article:author" content="MisterTian">
<meta property="article:tag" content="学习小结">
<meta property="article:tag" content="Java基础">
<meta property="article:tag" content="字符串">
<meta property="article:tag" content="正则表达式">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="https://gitee.com/xizhongren8980/xizhongren8980.git/2020/03/10/%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>正则表达式 | 一杯茶一包烟，一个BUG改一天</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/xizhongren8980/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">一杯茶一包烟，一个BUG改一天</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">收藏永不停止，学习永不开始</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/xizhongren8980/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/xizhongren8980/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/xizhongren8980/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/xizhongren8980/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/xizhongren8980/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://gitee.com/xizhongren8980/xizhongren8980.git/2020/03/10/%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/xizhongren8980/images/head.jpg">
      <meta itemprop="name" content="MisterTian">
      <meta itemprop="description" content="一个小菜鸟">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="一杯茶一包烟，一个BUG改一天">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          正则表达式
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
              

              <time title="创建时间：2020-03-10 13:50:11 / 修改时间：15:05:44" itemprop="dateCreated datePublished" datetime="2020-03-10T13:50:11+08:00">2020-03-10</time>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>正则表达式是一种强大且灵活的文本处理工具。它提供了一种完全通用的方式，能够解决字符串处理相关的问题：匹配、选择、编辑以及验证。<a id="more"></a></p>
<p><strong>举例</strong></p>
<ul>
<li><p><code>-？</code>表示字符串可能有一个负号在前面</p>
</li>
<li><p><code>\d</code>表示一位数字，不过特殊的是Java对反斜线\有不同的处理方式。在其他语言中，<code>\\</code>表示<code>我想要在正则表达式中插入一个普通的反斜线，请不要给它任何特殊的意义</code>，而在Java中<code>\\</code>表示的是<code>我要插入一个正则表达式的反斜线，所以其后的字符具有特殊的意义</code>。例如Java表示一位数字，正则表达式应该为<code>\\d</code>。</p>
</li>
<li><p><code>-？\\d+</code>表示<code>可能有一个负号，后面跟着一位或多位数字</code>。其中<code>+</code>表示<code>一个或多个之前的表达式</code>。</p>
</li>
<li><p><code>(-|\+)?\d+</code>表示<code>字符串的起始字符可能是一个-或者+或者都没有</code>，由于字符<code>+</code>在正则表达式中有特殊的意义，所以必须使用<code>\\</code>将其转义，使之成为表达式中的一个普通字符。在表达式中，括号有着分组的效果，竖直线<code>|</code>表示或操作。</p>
</li>
</ul>
<p><strong>利用Sting内建功能进行测试</strong></p>
<pre>
public class Test1 {
    public static void main(String[] args) {
        System.out.println("-1234".matches("-?\\d+"));
        System.out.println("5678".matches("-?\\d+"));
        System.out.println("+857".matches("-?\\d+"));
        System.out.println("\\".matches("\\\\"));
        System.out.println("+857".matches("(-|\\+)?\\d+"));//字符串的起始字符可能是一个-或者+或者都没有
    }
}
</pre>
<p>输出</p>
<pre>
true
true
false
true
true
</pre>

<p><strong>String类自带的正则表达式方法——split()方法</strong></p>
<p>基本功能是将字符串从正则表达式匹配的地方切开。</p>
<pre>
public class Test1 {
    public static String s = "Then, when you have found the shrubbery, " +
            "you must cut down the mightiest tree in the forest... with... a herring!";

    public static void split(String regex) {
        System.out.println(
                Arrays.toString(s.split(regex))
        );
    }

    public static void main(String[] args) {
        split(" ");
        split("\\W+");      //表示一个或多个非单词字符（W大写）
        split("n\\W+");     //表示字符n后面跟着一个或多个非单词字符（W大写）
        split("\\w+");      //表示一个或多个单词字符
    }
}
</pre>

<p>输出：</p>
<pre>
[Then,, when, you, have, found, the, shrubbery,, you, must, cut, down, the, mightiest, tree, in, the, forest..., with..., a, herring!]

[Then, when, you, have, found, the, shrubbery, you, must, cut, down, the, mightiest, tree, in, the, forest, with, a, herring]

[The, whe, you have found the shrubbery, you must cut dow, the mightiest tree i, the forest... with... a herring!]

[, , ,  ,  ,  ,  ,  , , ,  ,  ,  ,  ,  ,  ,  ,  ,  , ... , ... ,  , !]
</pre>

<p>可以看出，在原始字符串中，与正则表达式匹配的地方，在输出结果中都不见了。</p>
<p>另外，String类自带的正则表达式方法是“替换”，例如：</p>
<pre>
System.out.println(s.replaceFirst("f\\w+", "located"));//w小写
System.out.println(s.replaceAll("shrubbery|tree|herring", "banana"));
</pre>

<p>输出：</p>
<pre>
Then, when you have located the shrubbery, you must cut down the mightiest tree in the forest... with... a herring!
Then, when you have found the banana, you must cut down the mightiest banana in the forest... with... a banana!
</pre>

<p>符合条件的就被替换了。</p>
<p><strong>附部分常用表达式：</strong></p>
<pre><code>表达式        |    含义
:--:        |    :--:
\t            |    制表符Tab
\r            |    回车
\n            |    换行符
\e          |    转义（Escape）
\s            |    空白符（空格、Tab、换行、换页和回车）
\S            |    非空白符（同[^\s]）
\d            |    数字
\D            |    非数字
\w            |    词字符（同[a-zA-Z0-9]）
\W            |    非词字符
.           |    任意字符
[abc]       |    包含a、b、c的任何字符
[^abc]      |    除了a、b、c之外的任何字符（否定）
[a-zA-Z]    |    从a到z或者从A到Z的任何字符（范围）
[abc[hij]]  |    任意a、b、c、h、i和j字符（合并）
[a-z&amp;&amp;[hij]]|    任意h、i或j</code></pre>
    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/xizhongren8980/tags/%E5%AD%A6%E4%B9%A0%E5%B0%8F%E7%BB%93/" rel="tag"># 学习小结</a>
              <a href="/xizhongren8980/tags/Java%E5%9F%BA%E7%A1%80/" rel="tag"># Java基础</a>
              <a href="/xizhongren8980/tags/%E5%AD%97%E7%AC%A6%E4%B8%B2/" rel="tag"># 字符串</a>
              <a href="/xizhongren8980/tags/%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F/" rel="tag"># 正则表达式</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/xizhongren8980/2020/03/09/Java%E6%8C%81%E6%9C%89%E5%AF%B9%E8%B1%A1%E6%96%B9%E5%BC%8F%E5%B0%8F%E7%BB%93/" rel="prev" title="Java持有对象方式小结">
      <i class="fa fa-chevron-left"></i> Java持有对象方式小结
    </a></div>
      <div class="post-nav-item">
    <a href="/xizhongren8980/2020/03/16/Java%E5%9F%BA%E7%A1%80%E6%8E%92%E5%BA%8F%E7%AE%97%E6%B3%95/" rel="next" title="Java基础算法复习">
      Java基础算法复习 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="MisterTian"
      src="/xizhongren8980/images/head.jpg">
  <p class="site-author-name" itemprop="name">MisterTian</p>
  <div class="site-description" itemprop="description">一个小菜鸟</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/xizhongren8980/archives/">
        
          <span class="site-state-item-count">57</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/xizhongren8980/categories/">
          
        <span class="site-state-item-count">7</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/xizhongren8980/tags/">
          
        <span class="site-state-item-count">101</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>


  <div class="links-of-blogroll motion-element">
    <div class="links-of-blogroll-title"><i class="fa fa-link fa-fw"></i>
      友情链接
    </div>
    <ul class="links-of-blogroll-list">
        <li class="links-of-blogroll-item">
          <a href="https://mistertian8980.github.io/" title="https:&#x2F;&#x2F;mistertian8980.github.io&#x2F;" rel="noopener" target="_blank">Github博客</a>
        </li>
    </ul>
  </div>

      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">MisterTian</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

        








      </div>
    </footer>
  </div>

  
  <script size="300" alpha="0.6" zIndex="-1" src="/xizhongren8980/lib/canvas-ribbon/canvas-ribbon.js"></script>
  <script src="/xizhongren8980/lib/anime.min.js"></script>
  <script src="/xizhongren8980/lib/velocity/velocity.min.js"></script>
  <script src="/xizhongren8980/lib/velocity/velocity.ui.min.js"></script>

<script src="/xizhongren8980/js/utils.js"></script>

<script src="/xizhongren8980/js/motion.js"></script>


<script src="/xizhongren8980/js/schemes/pisces.js"></script>


<script src="/xizhongren8980/js/next-boot.js"></script>


  <script defer src="//cdn.jsdelivr.net/gh/theme-next/theme-next-three@1/three.min.js"></script>
    <script defer src="//cdn.jsdelivr.net/gh/theme-next/theme-next-three@1/canvas_lines.min.js"></script>


  




  
<script src="/xizhongren8980/js/local-search.js"></script>













  

  

</body>
</html>
